"""
自定义命令行命令
"""
import click
import subprocess
import os
from app import db
from app.models.user import User

def register_commands(app):
    """注册所有自定义命令"""
    
    @app.cli.command('init-db')
    def init_db():
        """装饰器: Flask CLI命令，用于初始化数据库表结构
        
        执行data目录下的SQL脚本创建所有数据库表
        只支持MySQL数据库
        """
        try:
            # 获取数据库配置
            db_url = app.config['SQLALCHEMY_DATABASE_URI']
            if db_url.startswith('mysql+pymysql://'):
                # 解析数据库连接信息
                auth_part = db_url.split('@')[0].replace('mysql+pymysql://', '')
                user_pass = auth_part.split(':')
                user = user_pass[0]
                password = user_pass[1].split('/')[0]
                
                # 获取SQL脚本路径
                basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
                sql_file = os.path.join(basedir, 'data', 'create_database.sql')
                
                # 使用MySQL命令行工具执行SQL脚本
                cmd = f'mysql -u{user} -p{password} < {sql_file}'
                result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
                
                if result.returncode == 0:
                    click.echo('数据库表结构已成功初始化。')
                else:
                    click.echo(f'初始化数据库时出错: {result.stderr}')
            else:
                click.echo('只支持MySQL数据库初始化。')
        except Exception as e:
            click.echo(f'执行SQL脚本时出错: {e}')
    
    @app.cli.command('create-admin')
    @click.argument('username')
    @click.argument('email')
    @click.argument('password')
    def create_admin(username, email, password):
        """装饰器: Flask CLI命令，用于创建管理员用户
        
        参数通过命令行参数传入：
        - username: 用户名
        - email: 电子邮件
        - password: 密码
        """
        user = User(username=username, email=email, password=password)
        db.session.add(user)
        db.session.commit()
        click.echo(f'管理员用户 {username} 创建成功!')
    
    @app.cli.command('seed-data')
    def seed_data():
        """装饰器: Flask CLI命令，用于填充测试数据
        
        执行data目录下的seed_data.sql脚本插入测试数据
        只支持MySQL数据库
        """
        click.echo('开始填充测试数据...')
        try:
            # 获取数据库配置
            db_url = app.config['SQLALCHEMY_DATABASE_URI']
            if db_url.startswith('mysql+pymysql://'):
                # 解析连接信息
                auth_part = db_url.split('@')[0].replace('mysql+pymysql://', '')
                user_pass = auth_part.split(':')
                user = user_pass[0]
                password = user_pass[1].split('/')[0]
                
                # 获取SQL脚本路径
                basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
                sql_file = os.path.join(basedir, 'data', 'seed_data.sql')
                
                # 执行SQL脚本
                cmd = f'mysql -u{user} -p{password} zhiyi < {sql_file}'
                result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
                
                if result.returncode == 0:
                    click.echo('测试数据填充完成！')
                    click.echo('\n以下是可用的测试账号：')
                    click.echo('管理员：admin@example.com / adminpassword')
                    for i in range(1, 6):
                        click.echo(f'用户{i}：user{i}@example.com / password{i}')
                else:
                    click.echo(f'填充数据时出错: {result.stderr}')
            else:
                click.echo('只支持MySQL数据库填充。')
        except Exception as e:
            click.echo(f'执行SQL脚本时出错: {e}') 